package com.yingda.electronicscaleadvices.utils;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.speech.tts.TextToSpeech;
import android.util.Log;

import java.util.Locale;

public class TTSutils {

    private static TextToSpeech textToSpeech;
    public static final String TAG ="TTSutils";

    private Handler mHandler = new Handler(Looper.getMainLooper());

    private TTSutils(){}

    /** 实例对象, 这里还没有添加volatile关键字 */
    private static TTSutils instance = null;

    /**
     * 获取对象: 将方法上的synchronized移至内部
     * @return instance 本类的实例
     */
    public static TTSutils getInstance() {
        // 先判断实例是否存在
        if (instance == null) {
            // 加锁创建实例
            synchronized (TTSutils.class) {
                // 再次判断, 因为可能出现某个线程拿了锁之后, 还没来得及执行初始化就释放了锁,
                // 而此时其他的线程拿到了锁又执行到此处 ==> 这些线程都会创建一个实例, 从而创建多个实例对象
                if (instance == null) {
                    instance = new TTSutils();

                }
            }
        }
        return instance;
    }

    public   void initTTS(Context context) {
        //实例化自带语音对象
        textToSpeech = new TextToSpeech(context, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status == textToSpeech.SUCCESS) {
                    // Toast.makeText(MainActivity.this,"成功输出语音",
                    // Toast.LENGTH_SHORT).show();
                    // Locale loc1=new Locale("us");
                    // Locale loc2=new Locale("china");

                    textToSpeech.setPitch(1.0f);//方法用来控制音调
                    textToSpeech.setSpeechRate(1.0f);//用来控制语速

                    //判断是否支持下面两种语言
                    int result1 = textToSpeech.setLanguage(Locale.CHINA);
//                    int result2 = textToSpeech.setLanguage(Locale.
//                            SIMPLIFIED_CHINESE);
//                    boolean a = (result1 == TextToSpeech.LANG_MISSING_DATA || result1 == TextToSpeech.LANG_NOT_SUPPORTED);
//                    boolean b = (result2 == TextToSpeech.LANG_MISSING_DATA || result2 == TextToSpeech.LANG_NOT_SUPPORTED);
//
//                    Log.i("zhh_tts", "US支持否？--》" + a +
//                            "\nzh-CN支持否》--》" + b);

                } else {
                    Log.i("zhh_tts", "onInit: " + "数据丢失或不支持");
                }

            }
        });


    }

    public void startAuto(String data) {
        // 设置音调，值越大声音越尖（女生），值越小则变成男声,1.0是常规
        textToSpeech.setPitch(1.0f);
        // 设置语速
        textToSpeech.setSpeechRate(1.0f);
        textToSpeech.speak(data,//输入中文，若不支持的设备则不会读出来
                TextToSpeech.QUEUE_FLUSH, null);

    }


    public void onStop() {
        if (textToSpeech!=null){
            textToSpeech.stop(); // 不管是否正在朗读TTS都被打断
            textToSpeech.shutdown(); // 关闭，释放资源
        }


    }
}
